import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_k_chart/chart_style.dart';
import 'package:flutter_k_chart/flutter_k_chart.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'package:trade/data/model/user_model.dart';
import 'package:trade/pages/trading_page/model/trading_model.dart';
import 'package:trade/pages/trading_page/view/drawer_item.dart';
import 'package:trade/pages/trading_page/view/period_bar.dart';
import 'package:trade/theme/app_colors.dart';
import 'package:trade/widgets/loading/loading_util.dart';
import 'dart:async';

class TradingPage extends StatefulWidget {
  @override
  _TradingPageWrapperState createState() => _TradingPageWrapperState();
}

const double kKChartHeight = 300;

class _TradingPageWrapperState extends State<TradingPage> {
  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (content, UserModel user, _) {
        return _TradingPageContent(user);
      },
    );
  }

}

class _TradingPageContent extends StatefulWidget {
  final UserModel user;

  const _TradingPageContent(this.user, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TradingPageState();
  }

}

class _TradingPageState extends State<_TradingPageContent>  with TickerProviderStateMixin{
  TradingModel _model = TradingModel();
  late AnimationController _chartController;
  late AnimationController _chartController1;
  @override
  void initState() {

    _chartController = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 500),
        lowerBound: double.negativeInfinity,
        upperBound: double.infinity);
    _chartController1 = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 500),
        lowerBound: double.negativeInfinity,
        upperBound: double.infinity);

    _chartController.addStatusListener((status) {

    });

    super.initState();
    _initData();
  }

  void _initData() async {
    _model.token = widget.user.info.token;
    showLoading();
    await _model.getKlineData();
    dismissLoading();
    _model.notifyTradePairs = _model.tradePairs;
    _startRefreshKlineData();
  }

  Timer? timer;
  ///
  void _startRefreshKlineData() {
    Timer.periodic(Duration(milliseconds: 1600), (timer) async {
        await _model.getKlineData(size: 1, updateLastLine: true);
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => _model,
      child: Scaffold(
        appBar: _buildAppBar(),
        drawer: _buildDrawer(),
        body: OrientationBuilder(
          builder: (context, orientation){
            return Padding(
              padding: EdgeInsets.only(bottom: MediaQueryData
                  .fromWindow(window)
                  .padding
                  .bottom),
              child: CustomScrollView(
                slivers: [
                orientation == Orientation.landscape ? SliverToBoxAdapter(child: SizedBox(),) :  SliverPersistentHeader(
                      pinned: true,
                      delegate: PeriodHeaderDelegate()),
                  SliverToBoxAdapter(child: _buildKChart(),),
                  SliverToBoxAdapter(child: SizedBox(height: 10,),),
                  SliverToBoxAdapter(child: _buildCustomKChart(),),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      centerTitle: false,
      toolbarHeight: 35,
      leading: Builder(
        builder: (context) {
          return IconButton(
            icon: SvgPicture.asset(
              'assets/svg/icon_filter.svg',
              width: 20,
              height: 20,
            ),
            onPressed: () {
              Scaffold.of(context).openDrawer();
            },
          );
        },
      ),
      title: Builder(
        builder: (context) {
          String pair = context.select<TradingModel, String>((value) =>
          value.currentPair);
          return Text(
            pair,
            style: TextStyle(
                color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
          );
        },
      ),
    );
  }

  Widget _buildKChart() {
    return Builder(
      builder: (context) {
        TradingModel model = context.watch<TradingModel>();
        return Container(
          height: kKChartHeight,
          margin: EdgeInsets.symmetric(horizontal: 10),
          width: double.infinity,
          child: KChartWidget(
            model.data,
            scrollXController: _chartController,
            isLine: false,
            mainState: MainState.NONE,
            secondaryState: SecondaryState.NONE,
            volState: VolState.NONE,
            fractionDigits: 4,
            chartColors: ChartColors(
              gridColor: appColors.gridColor,
              upColor: appColors.riseColor,
              dnColor: appColors.fallColor,
            ),

          ),
        );
      },
    );
  }

  Widget _buildCustomKChart() {
    return Builder(
      builder: (context) {
        TradingModel model = context.watch<TradingModel>();
        return Container(
          height: kKChartHeight,
          margin: EdgeInsets.symmetric(horizontal: 10),
          width: double.infinity,
          child: KChartWidget(
            model.data,
            scrollXController: _chartController1,
            isLine: false,
            mainState: MainState.MA,
            secondaryState: SecondaryState.NONE,
            volState: VolState.NONE,
            fractionDigits: 4,
            chartColors: ChartColors(
              gridColor: appColors.gridColor,
              upColor: appColors.riseColor,
              dnColor: appColors.fallColor,
              // ma5Color: Colors.red,
              // ma9Color: Colors.yellow,
              // ma20Color: Colors.white
            ),
            isCustomChart: true,
          ),
        );
      },
    );
  }

  Widget _buildDrawer() {
    return Drawer(
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(left: 15, bottom: 10),
              child: Text(
                '顺赢',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Divider(
              height: 1,
              color: Colors.grey[600],
            ),
            Expanded(
                child: Builder(
                  builder: (context) {
                    return ListView.builder(
                        padding: EdgeInsets.only(top: 10),
                        itemCount: context
                            .watch<TradingModel>()
                            .tradePairBeans
                            .length,
                        itemBuilder: (context, index) {
                          TradePairViewBean bean = context
                              .watch<TradingModel>()
                              .tradePairBeans[index];
                          return DrawerItem(
                            onTap: () {
                              context
                                  .read<TradingModel>()
                                  .currentPair = bean.name;
                              // _model.getList(
                              //     bean.name.toLowerCase(), "1min", "1000",widget.user.info.token);
                              Navigator.of(context).pop();
                            },
                            name: bean.name,
                            price: bean.price,
                            isRise: bean.isRise,
                          );
                        });
                  },
                )),
          ],
        ),
      ),
    );
  }

}


class PeriodHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double height;
  PeriodHeaderDelegate({this.height = 45 + 60});
  @override
  Widget build(BuildContext context, double shrinkOffset,
      bool overlapsContent) {
    return Column(
      children: [
        _buildMarketBar(context),
        _buildPeriodBar(context),
      ],
    );
  }

  Widget _buildMarketBar(BuildContext context){
    var model = context.watch<TradingModel>();
    return Container(
      height: 60,
      padding:  EdgeInsets.symmetric(horizontal: 15),
      color: appColors.backgroundColor,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
              flex: 3,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(
                    "${model.tickerBean.close.toStringAsFixed(2)}",
                    style: TextStyle(
                        fontSize: 20,
                        color: model.tickerBean.change < 0 ? appColors.fallColor : appColors.riseColor,
                        fontWeight: FontWeight.bold),
                  ),
                  Text(
                    "${(model.tickerBean.change * 100).toStringAsFixed(2)}%",
                    style: TextStyle(
                        fontSize: 14,
                        color: appColors.fallColor,
                        fontWeight: FontWeight.w500),
                  )
                ],
              )),
          Expanded(flex: 2, child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      "高",
                      style: TextStyle(
                          fontSize: 11,
                          color: appColors.white2,
                          fontWeight: FontWeight.w500),
                    ),
                    Text(
                      "低",
                      style: TextStyle(
                          fontSize: 11,
                          color: appColors.white2,
                          fontWeight: FontWeight.w500),
                    ),
                    Text(
                      "24H",
                      style: TextStyle(
                          fontSize: 11,
                          color: appColors.white2,
                          fontWeight: FontWeight.w500),
                    )
                  ],
                ),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      "${model.tickerBean.high.toStringAsFixed(2)}",
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: 11,
                          color: appColors.white1,
                          fontWeight: FontWeight.w500),
                    ),
                    Text(
                      "${model.tickerBean.low.toStringAsFixed(2)}",
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: 11,
                          color: appColors.white1,
                          fontWeight: FontWeight.w500),
                    ),
                    Text(
                      "${ model.tickerBean.amount.toStringAsFixed(0)}",
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: 11,
                          color: appColors.white1,
                          fontWeight: FontWeight.w500),
                    )
                  ],
                ),
              ),

              //
              // RichText(text: TextSpan(
              //   text: '高    ',
              //   style: TextStyle(fontSize: 12, color: appColors.white2),
              //   children: [
              //     TextSpan(text: "${model.tickerBean.high.toStringAsFixed(2)}",  style: TextStyle(fontSize: 12, color: appColors.white1)),
              //   ]
              // )),
              //
              // RichText(text: TextSpan(
              //     text: '低    ',
              //     style: TextStyle(fontSize: 12, color: appColors.white2),
              //     children: [
              //       TextSpan(text:  "${ model.tickerBean.low.toStringAsFixed(2)}",  style: TextStyle(fontSize: 12, color: appColors.white1)),
              //     ]
              // )),
              //
              // RichText(text: TextSpan(
              //     text: '24H    ',
              //     style: TextStyle(fontSize: 12, color: appColors.white2),
              //     children: [
              //       TextSpan(text:  "${ model.tickerBean.amount.toStringAsFixed(0)}",  style: TextStyle(fontSize: 12, color: appColors.white1)),
              //     ]
              // )),
            ],
          )
          )
        ],
      ),
    );
  }



  Widget _buildPeriodBar(BuildContext context) {
    var model = context.read<TradingModel>();
    return Container(
      height: 44,
      color: appColors.backgroundColor,
      child: PeriodBar(
        periodList: model.periodList,
        onPeriodChange: (p) {
          model.currentPeriod = p;
        }
      ),
      padding: const EdgeInsets.only(right: 10, top: 10, left: 10,),
      margin: const EdgeInsets.only(bottom: 1,),
    );
  }


  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      false;


}